<template>
  <div class="login">
    <header class="clear">
      <div class="fl">
        <img src="../../assets/img/logo_blue.png" alt="" style="height: 100%" />
      </div>
    </header>
    <div class="middle">
      <div class="themeCover">
        <div class="first">欢迎来到</div>
        <div class="second"></div>
        <div class="third">
          设备<br />
          资产管理系统
        </div>
        <div class="title">Equipment Asset Management System</div>
      </div>
      <div class="operate">
        <div class="loginForm" v-if="pageType == 'login'">
          <img src="../../assets/img/设备管理系统logo.png" alt="" />
          <div class="menu">
            <span class="click isActive">登录</span>
            <div></div>
            <span class="click" @click="() => (pageType = 'register')"
              >注册</span
            >
          </div>
          <el-form
            v-show="loginType == 'accountPassword'"
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="0px"
            class="demo-ruleForm"
          >
            <el-form-item prop="account">
              <el-input
                @focus="modifyFocusItem('account')"
                @blur="modifyFocusItem('')"
                type="text"
                v-model="ruleForm.account"
                placeholder="请输入账号"
                clearable
              >
                <img
                  slot="prefix"
                  :src="currentFocus==='account'?require('../../assets/img/手机号-激活.png'):require('../../assets/img/手机号-常态.png')"
                  alt=""
              /></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                @focus="modifyFocusItem('password')"
                @blur="modifyFocusItem('')"
                type="password"
                v-model="ruleForm.password"
                placeholder="请输入密码"
                clearable
              >
                <img
                  slot="prefix"
                  :src="currentFocus==='password'?require('../../assets/img/密码-激活.png'):require('../../assets/img/密码-常态.png')"
                  alt=""
                />
              </el-input>
            </el-form-item>
            <el-form-item prop="verityCode">
              <el-row>
                <el-col :span="16" class="phoneLogin click"
                  ><span @click="() => (loginType = 'phoneCode')"
                    >用手机验证码登录</span
                  ></el-col
                >
                <el-col :span="8" class="forgetPass click"
                  ><span @click="() => (pageType = 'resetPass')"
                    >忘记密码？</span
                  ></el-col
                >
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button
                class="w100 login-btn"
                style="
                  height: 44px;
                  margin-top: 10px;
                  font-size: 18px;
                  font-weight: 530;
                "
                type="primary"
                @click="submitForm();btnBlur($event)"
                @keyup.native.enter="submitForm()"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
          <el-form
            v-show="loginType == 'phoneCode'"
            :model="phoneForm"
            :rules="phoneRules"
            ref="phoneForm"
            label-width="0px"
            class="demo-ruleForm"
          >
            <el-form-item prop="phone">
              <el-input
                @focus="modifyFocusItem('account')"
                @blur="modifyFocusItem('')"
                type="text"
                v-model="phoneForm.phone"
                placeholder="请输入手机号码"
                clearable
              >
                <img
                  slot="prefix"
                  :src="currentFocus==='account'?require('../../assets/img/手机号-激活.png'):require('../../assets/img/手机号-常态.png')"
                  alt=""
                />
              </el-input>
            </el-form-item>
            <el-form-item prop="verityCode">
              <el-input
                @focus="modifyFocusItem('verifyNum')"
                @blur="modifyFocusItem('')"
                v-model="phoneForm.verityCode"
                placeholder="请输入验证码"
                clearable
              >
                <img
                  slot="prefix"
                  :src="currentFocus==='verifyNum'?require('../../assets/img/验证码-激活.png'):require('../../assets/img/验证码-常态.png')"
                  alt=""
                />
                <span
                  v-show="sendAuthCode"
                  slot="suffix"
                  class="code"
                  @click="getVerityCode"
                  >获取验证码</span
                >
                <span
                  v-show="!sendAuthCode"
                  slot="suffix"
                  class="resetGet"
                  :class="{ allow: authTime == 0 }"
                  @click="getVerityCode"
                  >重新获取{{ codeCountNum() }}</span
                >
              </el-input>
            </el-form-item>
            <el-form-item prop="verityCode">
              <el-row>
                <el-col :span="16" class="phoneLogin click"
                  ><span @click="() => (loginType = 'accountPassword')"
                    >用账号密码登录</span
                  ></el-col
                >
                <el-col :span="8" class="forgetPass click"
                  ><span @click="() => (pageType = 'resetPass')"
                    >忘记密码？</span
                  ></el-col
                >
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button
                class="w100 login-btn"
                style="
                  height: 44px;
                  margin-top: 10px;
                  font-size: 18px;
                  font-weight: 530;
                "
                type="primary"
                @click="phoneLogin();btnBlur($event)"
                @keypup.native.enter="phoneLogin()"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <register
          v-else-if="pageType == 'register'"
          :currentFocus="currentFocus"
          @clickLogin="() => (pageType = 'login')"
          @modifyFocusItem="modifyFocusItem"
        ></register>
        <forgetPassword
          v-else
          @clickLogin="() => (pageType = 'login')"
          @goBack="() => (pageType = 'login')"
        ></forgetPassword>
      </div>
    </div>
    <footer class="w1200">
      用户手册 | 推荐浏览器（ 谷歌浏览器 )， 360极速浏览器
    </footer>
  </div>
</template>

<script>
import {
  outStaffLogin,
  outStaffLoginByPhone,
  getPhoneLoginCode,
} from "@/api/login.js";
import register from "./register.vue";
import forgetPassword from "./forgetPassword";
export default {
  components: { register, forgetPassword },
  data() {
    return {
      // 当前选中input项
      currentFocus: '',
      sendAuthCode: true,
      authTime: 0,
      timer: null,
      codeUrl: null,
      pageType: "login",
      loginType: "accountPassword",
      ruleForm: {
        account: "",
        password: "",
        //verityCode: "",
      },
      rules: {
        account: [{ required: true, message: "请输入账号", trigger: "change" }],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
        ],
        // verityCode: [
        //   { required: true, message: "请输入验证码", trigger: "change" },
        // ],
      },
      phoneForm: {
        phone: "",
        verityCode: "",
      },
      phoneRules: {
        phone: [
          { required: true, message: "请输入账号", trigger: "change" },
          {
            message: "请输入正确的手机号码",
            trigger: "blur",
            validator: (rule, value, callback) => {
              var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
              if (!myreg.test(value)) {
                return callback(new Error("请输入正确的11位手机号码"));
              } else {
                callback();
              }
            },
          },
        ],
        verityCode: [
          { required: true, message: "请输入验证码", trigger: "change" },
        ],
      },
    };
  },
  created() {
    //this.getCode();
  },
  mounted() {
    document.onkeydown = () => {
      var key = window.event.keyCode;
      if (key == 13) {
        if (this.loginType == "accountPassword") {
          this.submitForm();
        } else {
          this.phoneLogin();
        }
      }
    };
  },
  methods: {
    //获取验证码倒计时
    codeCountNum() {
      if (this.authTime == 0) {
        return "";
      } else {
        return `(${this.authTime}s)`;
      }
    },
    btnBlur(e) {
      // el-button按钮点击后默认处于focus选中状态，手动取消掉按钮选中状态
      let target = e.target
      if(target.nodeName === 'SPAN') {
        target = e.target.parentNode
      }
      target.blur()
    },
    //账号密码登录
    submitForm() {
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          try {
            this.$store.commit("SET_CURRENTINFO", null);
            this.$utils.clearUserInfo();
            const formData = {
              account: this.ruleForm.account,
              verityCode: this.ruleForm.verityCode,
            };
            formData.password = await this.$utils.encryptPassword(
              this.ruleForm.password
            );
            let res = await outStaffLogin(formData);
            if (res.code == 200) {
              if (localStorage.getItem("SKIP_SIGN")) {
                this.$store
                  .dispatch("GetUserInfo")
                  .then((res) => {
                    this.$router.push({
                      path: "/workStation",
                    });
                    localStorage.removeItem("SKIP_SIGN");
                  })
                  .catch((error) => {});
              } else {
                this.$router.push({
                  path: "/appChange",
                  // query: {
                  //   account: res.data,
                  // },
                });
              }
            }
          } catch (error) {
            this.getCode();
          }
        } else {
          return false;
        }
      });
    },
    //手机验证码登录
    phoneLogin() {
      this.$refs["phoneForm"].validate(async (valid) => {
        if (valid) {
          try {
            this.$store.commit("SET_CURRENTINFO", null);
            this.$utils.clearUserInfo();
            const formData = {
              phone: this.phoneForm.phone,
              verityCode: this.phoneForm.verityCode,
            };
            let res = await outStaffLoginByPhone(formData);
            if (res.code == 200) {
              if (localStorage.getItem("SKIP_SIGN")) {
                this.$store
                  .dispatch("GetUserInfo")
                  .then((res) => {
                    this.$router.push({
                      path: "/workStation",
                    });
                    localStorage.removeItem("SKIP_SIGN");
                  })
                  .catch((error) => {});
              } else {
                this.$router.push({
                  path: "/appChange",
                  // query: {
                  //   account: res.data,
                  // },
                });
              }
            }
          } catch (error) {
            this.getCode();
          }
        } else {
          return false;
        }
      });
    },
    //获取图片验证码
    async getCode() {
      let url = "eam-service-system/system/staff/verifyCode";
      this.codeUrl = await this.$utils.echoImg(null, url);
    },
    //获取短信验证码
    getVerityCode() {
      if (this.phoneForm.phone != "") {
        getPhoneLoginCode({ phone: this.phoneForm.phone })
          .then((res) => {
            this.send();
          })
          .catch((error) => {});
      } else {
        this.$message.warning("请先输入手机号码");
      }
    },
    //验证码一分钟有效
    send() {
      if (!this.timer) {
        this.authTime = 60;
        this.sendAuthCode = false;
        this.timer = setInterval(() => {
          if (this.authTime > 0 && this.authTime <= 60) {
            this.authTime--;
          } else {
            this.sendAuthCode = true;
            clearInterval(this.timer); // 清除定时器
            this.timer = null;
          }
        }, 1000);
      }
    },
    // 变更选中项
    modifyFocusItem(type) {
      this.currentFocus = type
    }
  },
};
</script>

<style lang="less" scoped>
.login {
  width: 100%;
  height: 100%;
  background-image: url("../../assets/img/loginBackGround.png");
  position: relative;
  .fl {
    width: 165px;
    height: 40px;
    margin: 20px 0 0 20px;
  }
  .middle {
    position: absolute;
    width: 1440px;
    height: 680px;
    border-radius: 16px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    .themeCover {
      width: 900px;
      height: 680px;
      border-radius: 16px 0px 0px 16px;
      background: url(../../assets/img/systemTheme.png) no-repeat center,
        linear-gradient(135deg, #0858a9 0%, #478ed5 100%);
      box-shadow: 0px 0px 40px 0px rgba(51, 102, 204, 0.12);
      font-family: Source Han Sans CN;
      position: relative;
      .title {
        position: absolute;
        width: 440px;
        height: 50px;
        font-size: 24px;
        font-weight: 300;
        color: #ffffff;
        line-height: 50px;
        padding: 0 9px;
        border: 1px solid #ffffff;
        bottom: 53px;
        right: 51px;
      }
      .first {
        position: absolute;
        top: 75px;
        left: 71px;
        width: 145px;
        height: 34px;
        font-size: 36px;
        font-weight: 300;
        font-style: italic;
        color: #ffffff;
        line-height: 54px;
      }
      .second {
        position: absolute;
        top: 149px;
        left: 75px;
        width: 40px;
        height: 6px;
        background: #ffffff;
      }
      .third {
        text-align: left;
        position: absolute;
        top: 196px;
        left: 71px;
        width: 216px;
        height: 89px;
        font-size: 36px;
        font-weight: 400;
        color: #ffffff;
        line-height: 54px;
      }
    }
    .operate {
      width: 540px;
      height: 680px;
      background: #ffffff;
      box-shadow: 0px 0px 40px 0px rgba(51, 102, 204, 0.12);
      border-radius: 0px 16px 16px 0px;
      font-family: Source Han Sans CN;
      // /deep/.el-input input[type="password"] {
      //   font-family: '';
      //   letter-spacing: 3px;
      //   font-size: 30px;
      // }
      /deep/.el-input__inner {
        border: none;
        border-radius: 0px;
        border-bottom: 1px solid #999999;
        transition: border-color .2s;
      }
      /deep/.el-input__inner:hover {
        border-color: #333;
      }
      /deep/.el-input__inner:focus {
        border-bottom: 1px solid #0d60b4;
      }
      .menu {
        display: flex;
        width: 146px;
        height: 50px;
        margin: 40px 87px 30px 87px;
        justify-content: space-between;
        font-size: 28px;
        font-weight: 400;
        color: #999999;
        line-height: 27px;
        .isActive {
          color: #0d60b4;
        }
        div {
          width: 1px;
          height: 32px;
          background: #cccccc;
        }
      }
      .loginForm {
        margin: 71px 110px 154px 110px;
        height: 455px;
        text-align: center;
        .imgCode {
          color: #409eff;
          text-decoration: underline;
          cursor: pointer;
        }
        .phoneLogin {
          text-align: left;
          font-size: 14px;
          font-family: Source Han Sans CN;
          font-weight: 400;
          color: #0d60b4;
        }
        .forgetPass {
          text-align: right;
          font-size: 14px;
          font-weight: 400;
          color: #999999;
        }
        .resetGet {
          font-size: 16px;
          font-weight: 400;
          color: #cccccc;
        }
        .allow {
          cursor: pointer;
          color: #0d60b4;
        }
      }
    }
  }
  .w1200 {
    position: absolute;
    left: 50%;
    transform: translate(-50%);
    bottom: 20px;
  }
  .click {
    cursor: pointer;
  }
  .code {
    cursor: pointer;
    font-size: 16px;
    font-weight: 400;
    color: #0d60b4;
  }
  .demo-ruleForm /deep/ .el-input__inner {
    padding-left: 40px;
    font-size: 16px;
  }
  .demo-ruleForm /deep/ .el-input__suffix {
    .el-icon-circle-close:before {
      font-family: "iconfont";
      font-size: 16px;
      content: "\e6b6";
      color: rgba(152, 167, 185, 0.5);
    }
  }
}
.login-btn:focus {
  background-color: #0754A3;
}
.login-btn:active {
  background-color: #00468E;
}
</style>